/* eslint-disable multiline-ternary */
import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import styles from './index.module.scss'
type Props = {
  type: '' | 'name' | 'intro'
  hideInput: () => void,
  onUpdate:(key:string, value:string)=>void
}
const EditInput = ({ type, hideInput, onUpdate }: Props) => {
  // 取出数据
  const profile = useSelector((state: RootState) => state.profile.profile)
  const [name, setName] = useState(profile.name)
  const [intro, setIntro] = useState(profile.intro)

  // 引用
  const refInput = useRef<InputRef>(null)
  const refTextArea = useRef<TextAreaRef>(null)
  useEffect(() => {
    if (type === 'name') {
      refInput.current?.focus()
    } else {
      refTextArea.current?.focus()
      // textArea获取焦点时，光标默认在最前面
      document.querySelector('textarea')?.setSelectionRange(-1, -1)
    }
  }, [type])
  const onClick = () => {
    if (type === 'name') {
      onUpdate(type, name)
    } else {
      onUpdate(type, intro)
    }
  }
  return (
    <div className={styles.root}>
      <NavBar
        onBack={hideInput}
        className="navbar"
        right={<span className="commit-btn" onClick={onClick}>提交</span>}>
        编辑 {type === 'name' ? '昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>{type === 'name' ? '昵称' : '简介'}</h3>

        {type === 'name' ? (
          <div className="input-wrap">
            <Input
              value={name}
              ref={refInput}
              onChange={(val) => setName(val)}
              placeholder="请输入"
            />
          </div>
        ) : (
          <TextArea
          ref={refTextArea}
            className="textarea"
            placeholder="请输入简介"
            value={intro}
            onChange={(val) => setIntro(val)}
            showCount
            maxLength={99}
          />
        )}
      </div>
    </div>
  )
}

export default EditInput
